package com.doudou.collection.domain.service.admin.impl;

import com.doudou.collection.dao.mapper.admin.SysMenuMapper;
import com.doudou.collection.dao.mapper.admin.SysRoleMapper;
import com.doudou.collection.domain.service.admin.SysRoleService;
import com.doudou.collection.infrastructure.common.pojo.vo.PageData;
import com.doudou.collection.infrastructure.common.security.CurrentPrincipal;
import com.doudou.collection.infrastructure.common.security.SecurityUtils;
import com.doudou.collection.infrastructure.common.util.PageInfoToPageDataConverter;
import com.doudou.collection.orm.dto.admin.role.RoleQueryDTO;
import com.doudou.collection.orm.vo.admin.SysRoleVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SysRoleServiceImpl
 * @Description 后台角色业务实现类
 * @Author blue sky
 * @Date 2023/6/26 23:52
 * @Version 1.0
 */
@Slf4j
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<String> getRolePermission(CurrentPrincipal user) {
        List<String> roles = new ArrayList<>();
        // 管理员拥有所有权限
        if (SecurityUtils.isAdmin(user.getUserId())) {
            roles.add("admin");
        } else {
            roles.addAll(listRolePermissionByUserId(user.getUserId()));
        }
        return roles;
    }

    @Override
    public List<String> getMenuPermission(CurrentPrincipal user) {
        List<String> perms = new ArrayList<>();
        // 管理员拥有所有权限
        if (SecurityUtils.isAdmin(user.getUserId())) {
            perms.add("*:*:*");
        } else {
            perms.addAll(sysMenuMapper.listMenuTreeByUserId(user.getUserId()));
        }
        return perms;
    }

    @Override
    public PageData<SysRoleVO> list(RoleQueryDTO roleQueryDTO) {
        log.debug("正在处理【获取所有角色】业务，参数：{}", roleQueryDTO);
        PageHelper.startPage(roleQueryDTO.getPageNum(), roleQueryDTO.getPageSize());
        List<SysRoleVO> list = sysRoleMapper.list(roleQueryDTO);
        PageInfo<SysRoleVO> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverter.convert(pageInfo);
    }

    @Override
    public List<String> listRolePermissionByUserId(Long userId) {
        List<String> roles = sysRoleMapper.listRolePermissionByUserId(userId);
        return roles;
    }
}
